package com.beidouin.GnssMain.sample;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.beidouin.GnssMain.EventSerialReceive;
import com.beidouin.GnssMain.SerialPortReader;
import com.beidouin.GnssMain.models.PilotInfo;
import com.beidouin.GnssMain.R;
import com.beidouin.GnssMain.utils.FileUtils;
import com.friendlyarm.AndroidSDK.FileCtlEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


public class NmeaActivity extends SerialPortActivity implements View.OnClickListener {

    static final int MAX_VIEW_LENGTH = 500;
    private RadioButton mSerial_gps11;
  //  private RadioButton mSerial_gps12;
    private RadioButton mSerial_gps23;
   // private RadioButton mSerial_gps24;
    private RadioButton mSerial_ttl1;
    private RadioButton mSerial_ttl2;
    private RadioButton mSerial_uarte;
    private RadioButton mSerial_uartf;
    private Button stopButton;
    private Button clearButton;
    private SharedPreferences.Editor edit;
    private SharedPreferences preferences;
    List<String> dataList;

    String receiveData;//GNGGA-0;GPGGA-1;GPRMC-2;GNRMC-3;BDGSV-4;GPGSV-5;GPGSA-6;BDGSA-7;
    ListView viewList;
    ArrayAdapter<String> viewArray;
    boolean isDataRefreshing;
  //  boolean isSelectCOM1 = true;
    private Button mSwitchButton;
    int devFD = -1;
    private String s;
    private String path;
    private String fileContent;

    @Override
    public void onDestroy() {
        if (devFD >= 0) {
            HardwareControler.close(devFD);
            devFD = -1;
        }
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nmea);
        path = Environment.getExternalStorageDirectory().getPath();
        initView();

        //sp保存
        SharedPreferences pref = getSharedPreferences("APP", MODE_PRIVATE);
        boolean gps11Boolean = pref.getBoolean("gps11", false);
       // boolean gps12Boolean = pref.getBoolean("gps12", false);
        boolean gps23Boolean = pref.getBoolean("gps23", false);
        //boolean gps24Boolean = pref.getBoolean("gps24", false);
        boolean ttl1Boolean = pref.getBoolean("ttl1", false);
        boolean ttl2Boolean = pref.getBoolean("ttl2", false);
        boolean uarteBoolean = pref.getBoolean("uarte", false);
        boolean uartfBoolean = pref.getBoolean("uartf", false);


        mSerial_gps11.setChecked(gps11Boolean);
     //   mSerial_gps12.setChecked(gps12Boolean);
        mSerial_gps23.setChecked(gps23Boolean);
      //  mSerial_gps24.setChecked(gps24Boolean);
        mSerial_ttl1.setChecked(ttl1Boolean);
        mSerial_ttl2.setChecked(ttl2Boolean);
        mSerial_uarte.setChecked(uarteBoolean);
        mSerial_uartf.setChecked(uartfBoolean);
    }

    private void initView() {
        stopButton = (Button) findViewById(R.id.stopButton);
        devFD = HardwareControler.open("/dev/i2c-0", FileCtlEnum.O_RDWR);
        int rew = HardwareControler.setI2CSlave(devFD, 0x29);//设置I2c通信硬件地址
        initBottomView();
        nmeaImage.setImageResource(R.drawable.icon_nmea_select);
        nmeaText.setTextColor(getResources().getColor(R.color.splash_bg));
        isDataRefreshing = true;
        clearButton = (Button) findViewById(R.id.clearButton);
        mSwitchButton = (Button) findViewById(R.id.switchButton);
        mSerial_gps11 = (RadioButton) findViewById(R.id.gps11);
      //  mSerial_gps12 = (RadioButton) findViewById(R.id.gps12);
        mSerial_gps23 = (RadioButton) findViewById(R.id.gps23);
     //   mSerial_gps24 = (RadioButton) findViewById(R.id.gps24);
        mSerial_ttl1 = (RadioButton) findViewById(R.id.ttl1);
        mSerial_ttl2 = (RadioButton) findViewById(R.id.ttl2);
        mSerial_uarte = (RadioButton) findViewById(R.id.uarte);
        mSerial_uartf = (RadioButton) findViewById(R.id.uartf);

        stopButton.setOnClickListener(this);
        clearButton.setOnClickListener(this);
        mSwitchButton.setOnClickListener(this);
        dataList = new ArrayList<String>();
        receiveData = new String();
        receiveData = " ";
        viewList = (ListView) findViewById(R.id.nmea_list);
        viewArray = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
        viewList.setAdapter(viewArray);

    }
    private void dataRefresh() {
        dataList.add(receiveData);
        if (dataList.size() > MAX_VIEW_LENGTH) {
            dataList.remove(0);
        }
    }

    public void onEventMainThread(final EventSerialReceive event) {
        if (event.eventType == EventSerialReceive.EVENT_UPDATE_ACTIVITY) { //data from serial port
            if ((event.iData & EventSerialReceive.UPDATE_NMEA) != 0) {
                if (isDataRefreshing) {
                    receiveData = PilotInfo.getInstance().getDataString();
                    dataRefresh();
                    viewArray.notifyDataSetChanged();
                    viewList.setSelection(viewArray.getCount() - 1);
                }
            }
        }
    }

    public void showPopWin() {
         AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("切换串口中3秒内请勿切换页面")
//                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        Toast.makeText(AlertDialogActivity.this, "这是确定按钮", Toast.LENGTH_SHORT).show();

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        Toast.makeText(AlertDialogActivity.this, "这是取消按钮", Toast.LENGTH_SHORT).show();

                    }
                })
                .create();
        alertDialog2.setCancelable(false);//表示点空白处取消不了
        alertDialog2.show();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.stopButton: {
                isDataRefreshing = !isDataRefreshing;
                if (isDataRefreshing) {
                    stopButton.setText(" 暂停刷新 ");
                } else {
                    stopButton.setText(" 开始刷新 ");
                }
            }
            break;
            case R.id.clearButton: {
                dataList.clear();
                viewArray.notifyDataSetChanged();
            }
            break;
            //切换串口
            case R.id.switchButton:

               // showPopWin();
                //保存状态
                preferences = getSharedPreferences("APP", Context.MODE_PRIVATE);
                edit = preferences.edit();
                edit.putBoolean("gps11", mSerial_gps11.isChecked());//1-0
                edit.putBoolean("gps23", mSerial_gps23.isChecked());//1-1
         //       edit.putBoolean("gps24", mSerial_gps24.isChecked());//2-1
                edit.putBoolean("uarte", mSerial_uarte.isChecked());//1-2
                edit.putBoolean("uartf", mSerial_uartf.isChecked());//2-2
                edit.putBoolean("ttl", mSerial_ttl1.isChecked());//1-3
                edit.putBoolean("ttl1", mSerial_ttl2.isChecked());//2-3
                edit.commit();

                String fileContent = FileUtils.getFileContent(new File(path + "/storage/emulated/0/" + "iN6100_data/NMEA/", "NMEA.txt"));
                String[] split = fileContent.split(",");
                split.equals(fileContent);

                if (preferences.getBoolean("gps11", false)) {
                    s = "$CCSET,GPS11," + split[2];

                }
                if (preferences.getBoolean("gps23", false)) {
                    s = "$CCSET,GPS23," + split[2];

                }
                if (preferences.getBoolean("uarte", false)) {
                    s = "$CCSET,UARTE," + split[2];

                }
                if (preferences.getBoolean("ttl", false)) {
                    s = "$CCSET,TTL01," + split[2];
                }



                if (preferences.getBoolean("gps12", false)) {
                    s = "$CCSET,"+ split[1] + ",GPS12\r\n";

                }
                if (preferences.getBoolean("gps24", false)) {
                    s = "$CCSET,"+ split[1] + ",GPS24\r\n";

                }
                if (preferences.getBoolean("uartf", false)) {
                    s = "$CCSET,"+ split[1] + ",UARTF\r\n";

                }
                if (preferences.getBoolean("ttl1", false)) {
                    s = "$CCSET,"+ split[1] + ",TTL02\r\n";

                }
                FileUtils.writeTxtToFile(s, path+"/storage/emulated/0/"+"iN6100_data/NMEA/","NMEA.txt");
                SerialPortReader.getInstance().OpenSerialPort(1);
                SendI2cCmd(s);

                break;
        }
    }

    private boolean SendI2cCmd(String s) {
        boolean ret = true;
        byte[] bytes = s.getBytes();
        byte b;
        for (int i = 0; i < bytes.length; i++) {
            b = bytes[i];
            if (HardwareControler.I2CWriteByte(devFD, b, 20) != 0) {
                ret = false;
                break;
            }
        }
        return ret;
    }

    @Override
    protected void onResume() {
        super.onResume();

        fileContent = FileUtils.getFileContent(new File(path+"/storage/emulated/0/"+"iN6100_data/NMEA/","NMEA.txt"));
        Log.i("nmea.txt","====="+ fileContent.toString());


        if (fileContent.equals("$CCSET,GPS11,"+"GPS12\r\n")){
            mSerial_gps11.setChecked(true);
        }else if  (fileContent.equals("$CCSET,GPS23,"+"GPS12\r\n")){
            mSerial_gps23.setChecked(true);
        }else if  (fileContent.equals("$CCSET,UARTE," + "GPS12\r\n")){
            mSerial_uarte.setChecked(true);
        }else if  (fileContent.equals("$CCSET,TTL01," + "GPS12\r\n")){
            mSerial_ttl1.setChecked(true);
        }

        if (fileContent.equals("$CCSET,GPS11,"+"GPS24\r\n")){
            mSerial_gps11.setChecked(true);
        }else if  (fileContent.equals("$CCSET,GPS23,"+"GPS24\r\n")){
            mSerial_gps23.setChecked(true);
        }else if  (fileContent.equals("$CCSET,UARTE," + "GPS24\r\n")){
            mSerial_uarte.setChecked(true);
        }else if  (fileContent.equals("$CCSET,TTL01," + "GPS24\r\n")){
            mSerial_ttl1.setChecked(true);
        }

        if (fileContent.equals("$CCSET,GPS11,"+"UARTF\r\n")){
            mSerial_gps11.setChecked(true);
        }else if  (fileContent.equals("$CCSET,GPS23,"+"UARTF\r\n")){
            mSerial_gps23.setChecked(true);
        }else if  (fileContent.equals("$CCSET,UARTE," + "UARTF\r\n")){
            mSerial_uarte.setChecked(true);
        }else if  (fileContent.equals("$CCSET,TTL01," + "UARTF\r\n")){
            mSerial_ttl1.setChecked(true);
        }

        if (fileContent.equals("$CCSET,GPS11,"+"TTL02\r\n")){
            mSerial_gps11.setChecked(true);

        }else if  (fileContent.equals("$CCSET,GPS23,"+"TTL02\r\n")){
            mSerial_gps23.setChecked(true);
        }else if  (fileContent.equals("$CCSET,UARTE," + "TTL02\r\n")){
            mSerial_uarte.setChecked(true);
        }else if  (fileContent.equals("$CCSET,TTL01," + "TTL02\r\n")){
            mSerial_ttl1.setChecked(true);
        }
    }
}
